//
//  ComposeViewController.swift
//  Weobo
//
//  Created by lambo on 16/1/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    
    private lazy var keyBoardView: EmotionKeyBoardView=EmotionKeyBoardView{(em)->() in
        
        print(em)
        
        self.textView.insetText(em)
        
    }
    
    //MARK:选择图片
    @objc private func selectPicture() {
    
        print(__FUNCTION__)
        
        //更新图片选择器的视图的约束
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(KHeight/3*2)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            //强制刷新页面
            self.view.layoutIfNeeded()
        }
    
    
    }
    //MARK:选择自定义表情键盘
    @objc private func selectEmotion() {
        print(__FUNCTION__)
        print(textView.inputView)
        
        //取消第一响应者
        self.textView.resignFirstResponder()
        self.textView.inputView=self.textView.inputView == nil ? keyBoardView : nil
        
        //成为第一响应者
        self.textView.becomeFirstResponder()
    }
    
    @objc private func closeBtnClick() {
    
        print(__FUNCTION__)
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func sendBtnClick() {
        print(__FUNCTION__)
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        
        guard let token=UserAccountViewModel().token else{
            
            SVProgressHUD.showErrorWithStatus("暂未登录",maskType: .Gradient)
            return
            
        }
        
        
        let parameters = ["access_token": token,"status":textView.fullText()]
        if pictureSelectorVC.imageList.count != 0 {
            //获取图片的二进制数据
            let imageData=UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)!
            
            //调用上传图片的接口
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            NetworkTools.sharedTools.POST (urlString, parameters: parameters, constructingBodyWithBlock: { (fromData  ) -> Void in
            /*
            将要上传的二进制文件数据拼接到fromData中
            1.data:要上传的文件的二进制数据
            2.name:服务器接受的字段
            3.fileName:服务器存储的文件名,但是在这个地方可以"乱写",生成高清/中等/缩略图
            4.mineType:告诉服务器上传的文件类型
            5.图片:image/jpeg   不关注文件类型可以使用:application/octet-stream(八进制的流)
            
            */
           
            fromData.appendPartWithFileData(imageData, name: "pic", fileName: "x0", mimeType: "image/jpeg")
          
            
            }, progress: nil, success: { (_, result) -> Void in
                print(result)
                
                //消失当前的视图控制器
                SVProgressHUD.showSuccessWithStatus("发布成功",maskType: .Gradient)
                self.dismissViewControllerAnimated(true, completion: nil)
                
                
            }, failure: { (_, error) -> Void in
                print(error)
           })
        } else {
        
        NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
            
                //出现错误
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            
            }
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }
        
    
    }
    
}

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor=UIColor.whiteColor()
        
        /*
        1.iOS7.0以后出现的布局辅助系统指导
        1.1如果使用自动布局先添加顶部约束,就会开启顶部辅助系统
        1.2如果使用自动布局先添加底部约束,就会开启底部辅助系统
        */
      

        setupNavBar()
        setTextView()
        setToolBar()
        setSelectorVC()
        
        
        /*
        一个视图中如果有UINavgiationBar或者Toolbar注意:
        1.在iOS7.0以后滚动视图会根据是否有个 (UINavgiationBar 或者 UITabar) 修改scrollView的 contentInset
        2.self.automaticallyAdjustsScrollViewInsets  自动调整滚动视图的 contentInset
        
        3.注意: 从上往下开始进行布局
        */

        // Do any additional setup after loading the view.
        registerNotification()
    }
    @objc private func keyBoardChange(noti: NSNotification) {
    
        print(noti)
        
        //获取动画时间
        let duration=(noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //NSRect是一个结构体,结构体需要包装成NSValue
        let endRect=(noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //curve动画曲线值
        let curve=(noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offsetY = -KHeight + endRect.origin.y
        
        UIView.animateWithDuration(duration) { () -> Void in
          
             //设置动画曲线值 一旦设置动画曲线值 为 7  动画时间就无效
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            
            //修改底部约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view.snp_bottom).offset(offsetY)
            })
            
            //强制刷新
            self.view.layoutIfNeeded()
        }
    
    
    }
    
    private func registerNotification() {
    
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    
    }
    
    //移除通知
    deinit {
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    
    
    private func setTextView() {
        view.addSubview(textView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.right.equalTo(self.view)
            
            make.height.equalTo(KHeight/3)
        }
    
        //添加占位文本
        textView.addSubview(placeHoldrLabel)
        
        
        //占位文本约束
        placeHoldrLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    
    
    }

    //MARK:设置导航条
    private func setupNavBar() {
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeBtnClick")

        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendBtnClick")

        //1.禁用发送按钮
        navigationItem.rightBarButtonItem?.enabled=false
    
        //2.自定义titleView,默认为nil,注意不能直接addSubView
        let myView=UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //3.添加子控件
        let titleLabel=UILabel(title: "发表微博", fontSize: 17, color: UIColor.darkGrayColor())
        
        
        myView.addSubview(titleLabel)

        
        let nameLabel=UILabel(title: UserAccountViewModel().userName ?? "", fontSize: 14, color: UIColor.lightGrayColor())
        myView.addSubview(nameLabel)
        
        //4.设置布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
            
            
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
        
        //5.赋值
        navigationItem.titleView=myView
    
    
    }
    
    
    //MARK:懒加载视图
    //1.textView
    private lazy var textView: EmotionTextView = {
    
        let tv=EmotionTextView()
        //tv.text="请输入新鲜事"
        tv.font=UIFont.systemFontOfSize(18)
        tv.textColor=UIColor.darkGrayColor()
        tv.backgroundColor=UIColor.yellowColor()
        //开启垂直方向的弹簧效果
        tv.alwaysBounceVertical=true
        
        //设置代理
        tv.delegate=self
        
        //设置隐藏键盘的方式(iOS7.0以后的)
        tv.keyboardDismissMode = .OnDrag
        
        return tv
    
    
    }()
    //2.占位文本
    private lazy var placeHoldrLabel: UILabel = UILabel(title: "请输入新鲜事", fontSize: 18, color: UIColor.lightGrayColor())


    //3.底部工具条toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()

    //4.图片选择控制器
    private lazy var pictureSelectorVC: PictureSelectorViewController=PictureSelectorViewController()
}

//MARK:设置文本
extension ComposeViewController: UITextViewDelegate {


    func textViewDidChange(textView: UITextView) {
        //隐藏占位文本
        placeHoldrLabel.hidden=textView.hasText()
        
        //开始右边的导航按钮的交互
        navigationItem.rightBarButtonItem?.enabled=textView.hasText()
    }


}


//MARK:UI设置相关的方法
extension ComposeViewController {
    //2.设置添加图片选择器
    private func setSelectorVC() {
    
        //2.1添加视图控制器
        addChildViewController(pictureSelectorVC)
        
        //2.2添加控制器的视图
        view.addSubview(pictureSelectorVC.view)
        
        //2.3将toolBar移到视图顶部
        self.view.bringSubviewToFront(toolBar)
        
        //2.4设置约束
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }

    }
    
    //1.设置底部toolBar
    private func setToolBar() {
        
        //1.添加toolBar
        self.view.addSubview(toolBar)
        
        //2.设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
        }
        
        //3.设置toolBar子视图(actionName:代表选择的方法)
        var items = [UIBarButtonItem]()
        
let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmotion"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
        
            //获取图片名称
            let imageName=item["imageName"]
            let btn=UIButton(imageName: imageName, backImageName: nil)
            
            //注册添加点击事件
            if  let actionName = item["actionName"] {
                //Selector 会将字符自动转换为 Selector类型 不能够直接传递字符串的引用
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let item=UIBarButtonItem(customView: btn)
            
            
            //添加到数组里面
            items.append(item)
            
            //添加弹簧
            let space=UIBarButtonItem(barButtonSystemItem:
                .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        
        
        
        }
        
        //多了一个,需要把最后一个移除
        items.removeLast()
        
        //设置视图
        toolBar.items=items

    }

    
}

    